//var server = "http://127.0.0.1:801";
//var server = "http://192.168.3.8:801";
var server = "https://cloud.sh-huajusheng.cn";
var server2 = "https://yijun.sh-huajusheng.cn";
//var io = require('/libs/socket.io.xcx.min');
//var ioAT = require('/libs/socket.io.xcx.min');
//var socket = io('wss://cloud.sh-huajusheng.cn');
//var socketAT = io('wss://www.anteye.cn');
//let manager = plugin.getRecordRecognitionManager()
//即时通讯
// socketAT.on('connect', function () {
//   console.log('socketAT connect');
// });
//即时通讯
// socket.on('connect', function () {
//   console.log('socket connect');
// });
// socket.on('disconnect', function () {
//   socket.on('connect', function(){
//       console.log('socket reconnect')
//   });
// });
//var chatbot = requirePlugin("chatbot");
App({
  onLaunch: function () {
    var that = this;
    wx.getSystemInfo({
      success: e => {
        console.log(e)
        that.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        that.globalData.height = e.windowHeight;
        that.globalData.width = e.windowWidth;
        that.globalData.Custom = custom;
        that.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })

    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    const updateManager = wx.getUpdateManager();
    updateManager.onUpdateReady(function () {
      updateManager.applyUpdate()
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，开始重启应用',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            //updateManager.applyUpdate()
          }
        }
      })
    })
    that.checkSession()

  },
  setWXLocation: function () {
    var that = this;
    if (that.globalData.role_default == 'driver' && that.globalData.vehicleId) {
      if (that.globalData.userLocationBackground) {
        wx.startLocationUpdateBackground({
          success: function () {
            wx.onLocationChange(function (res) {
              console.log('location change', res)
              that.saveWXLocation(res.latitude, res.longitude, res.speed);
              wx.offLocationChange();
            })
            setInterval(function () {
              wx.onLocationChange(function (res) {
                console.log('location change', res)
                that.saveWXLocation(res.latitude, res.longitude, res.speed);
                wx.offLocationChange();
              })
            }, 120000); //120000
          }
        })
      } else {
        wx.getLocation({
          type: 'gcj02',
          success: function (res) {
            that.saveWXLocation(res.latitude, res.longitude, res.speed);
          }
        });
        setInterval(function () {
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              that.saveWXLocation(res.latitude, res.longitude, res.speed);
            }
          });
        }, 120000);
      }
    }
  },
  saveWXLocation: function (latitude, longitude, speed) {
    var that = this;
    that.globalData.latitude = latitude;
    that.globalData.longitude = longitude;
    wx.request({
      url: server + '/atapi/iot/setWXLocation',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {
        unionid: that.globalData.unionid,
        user_id: that.globalData.user_id,
        vehicleId: that.globalData.vehicleId,
        role: that.globalData.role_default,
        longitude: longitude,
        latitude: latitude,
        speed: speed
      },
      success: function (res) {
        //console.log(res);
        if (res.data.success) {
          console.log('WX' + that.globalData.vehicleId)
        }
      }
    })
  },
  checkSession: function () {
    // var that = this;
    // setInterval(function () {
    //   wx.request({
    //     url: server + '/api/checkSession',
    //     method: 'GET',
    //     header: {
    //       'content-type': 'application/json',
    //       'Cookie':that.globalData.cookie
    //     },
    //     success: function (res) {
    //       console.log(res);
    //       if (res.data.success) {

    //       }else{
    //         console.log('fail----fail')
    //         that.getUserInfo(function(){

    //         })
    //       }
    //     }
    //   })
    // }, 20000);
  },
  onShareAppMessage: function () {
    return {
      title: '小冷通TMS',
      path: '/pages/index/index'
    }
  },
  appName: '小冷通TMS',
  globalData: {
    CO_NAME:'华聚盛（上海）企业管理有限公司',
    userInfo: null,
    openid: null,
    unionid: null,
    userType: null,
    mobile: null,
    truename: "",
    vehicle: "",
    user_id: "",
    co_id: "",
    latitude: "",
    longitude: "",
    temperature: ""
  },
  //socket: socket,
  //socketAT: socketAT,
  server: server,
  server2: server2,
  getUserInfo: function (cb) {
    var that = this;
    //调用登录接口
    wx.login({
      success: function (res1) {
        console.log(res1)
        if (res1.code) {
          wx.request({
            url: server+"/tencent/wechat/wechatBind/"+res1.code,
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              console.log(res.data)
              if(res?.data?.result?.body){
              that.globalData.session_key = res.data.result.body.session_key;
              that.globalData.openid = res.data.result.body.openid;
              wx.request({
                url: server + '/auth/login',
                method: 'POST',
                header: {
                  'content-type': 'application/json'
                },
                data: {
                  openId: res.data.result.body.openid
                },
                success: function (res) {
                  console.log(res)
                  //that.globalData.cookie = res.header["set-cookie"] || res.header["Set-Cookie"];
                  //智能客服
                  // chatbot.init({
                  //   appid: "WwXuPkqTCSIwxhpgGwPgq1GXI4DiAd", //小程序示例账户，仅供学习和参考
                  //   openid: res.data.openid, //用户的openid，非必填，建议传递该参数
                  //   success: () => {}, //非必填
                  //   fail: error => {} //非必填
                  // });

                  //var roleData = res.data.roleData || [];
                  //that.globalData.roleData = roleData;
                  //that.globalData.unionid = res.data.unionid;
                  that.globalData.register = false;
                  if (res.data.success) {
                    var data = res.data.result || {};
                    that.globalData.register = true;
                    that.globalData.userData = data;
                    that.globalData.token = data.token;
                    that.globalData.phone = data.phone;
                    that.globalData.truename = data.truename;
                    that.globalData.user_id = data.userid;
                    that.globalData.CO_ID = data.co_id;
                    that.globalData.dept_code = data.dept_code;
                    that.globalData.dept_code = data.dept_name;
                    that.globalData.roles = data.roles||[];
                    that.globalData.name = data.name;
                    that.globalData.is_login = true;
                    that.globalData.admin = data.roles.indexOf('||admin|||') > -1 ? true : false;

                    // if (roleData.length > 0) {
                    //   for (var i = 0; i < roleData.length; i++) {
                    //     if (roleData[i].CO_ID == data.CO_ID && roleData[i].role == 'admin') {
                    //       that.globalData.coAdmin = true;
                    //       that.globalData.deleteRole = true;
                    //       that.globalData.price_schedule_show = true;
                    //     }
                    //     if (roleData[i].CO_ID == data.CO_ID && roleData[i].role == 'operation') {
                    //       that.globalData.deleteRole = true;
                    //       that.globalData.price_schedule_show = true;
                    //     }
                    //     if (roleData[i].CO_ID == data.CO_ID && data.CO_ID != 0 && roleData[i].is_login == 0) {
                    //       that.globalData.is_login = false;
                    //     }
                    //   }
                    // }
                    if(data.roles.indexOf('||driver|||') > -1){
                      wx.request({
                        url: server + '/zhc/datalist/getDataByListId',
                        method: 'POST',
                        header: {
                          'content-type': 'application/json',
                          'AUTHORIZATION':that.globalData.token
                        },
                        data:{
                          "list_id": "F905AEC8-5754-4B14-83E2-672E45717039",
                          "res": "47bb1f0ec0874fb5961186f86b97792e",
                          "page": {
                              "size": 1,
                              "current": 1,
                              "orders": [
                                  {
                                      "column": "a.ADD_TIME",
                                      "asc": "false"
                                  }
                              ]
                          },
                          "data": {
                              "field": "a.plate,a.driver,a.model,a.coord,a.district,a.total_oil,a.ADD_TIME,a.loadage,a.score,a.vehicle_register,a.vehicle_function,a.INSURANCE,a.tags,a.miles,a.plate_owner,a.temperature_current,a.oils,a.vehicle_size_out,a.vip,a.semitrailer_plate,a.loan_body,a.brand,a.loan_nper,a.province,a.latitude_current,a.iot_box,a.color,a.vehicleVolume,a.address,a.level,a.driver2,a.capacity_company,a.vip_to,a.is_work,a.photo,a.state,a.loan_month,a.ID,a.engineno,a.ischeck,a.buy_date,a.income_ratio,a.roadTC,a.longitude_current,a.cost,a.changeCompany,a.CO_ID,a.loan_first,a.carrier,a.station_address,a.last_keep_date,a.vin,a.approved_load,a.depreciation_ratio,a.truck_type,a.total_weight,a.vehicle_owner,a.img_vehicle_licence,a.mobile_warehouse,a.vehicleSizeWidth,a.vehicleSizeHeight,a.vehicleFunction,a.vehicleLength,a.vehicleSizeLength,a.plate_color,a.img_vehicle,a.station_coord,a.xyp_vehicle,a.operating_permit,a.contract,a.capacity_shipper,a.user_id,a.NO,a.depreciation_month_price,a.vehicle_spec_in,a.semitrailer,a.vehicleSource,a.tp_alarm,a.purchase_date,a.vehicle_key,a.max_speed,a.ADD_USER,a.purchase_price,a.is_oil,a.street,a.app_gps_first,a.vehicle_type,a.city,a.oldId,a.humidity_current,a.BE_DEL,a.DATA_CLIENT,a.DATA_DEPT,a.DATA_DEPT_TEXT,a.UPDATE_USER_NAME,a.DATA_ROLE,a.UPDATE_USER,a.ADD_USER_NAME,a.UPDATE_TIME,a.DATA_NO"
                          },
                          "repeat_field": [],
                          "condition": " d.phone='"+that.globalData.phone+"' ",
                          "virtual_field": [
                              {
                                  "relate": "LEFT JOIN",
                                  "res": "88e65a5ccd734a35a0cac74c9d58ff2e",
                                  "alias": "b",
                                  "on": "a.driver=b.ID",
                                  "type": "",
                                  "condition": "",
                                  "from_field": "name",
                                  "field_name": "name",
                                  "field_alias": "司机"
                              },
                              {
                                  "relate": "LEFT JOIN",
                                  "res": "88e65a5ccd734a35a0cac74c9d58ff2e",
                                  "alias": "d",
                                  "on": "a.driver=d.ID",
                                  "type": "",
                                  "condition": "",
                                  "from_field": "phone",
                                  "field_name": "phone",
                                  "field_alias": "手机号码"
                              }
                          ]
                      },
                        success: function (res) {
                          console.log(res)
                          console.log(res.data.result.records[0])
                          if(res?.data?.result?.records?.length > 0){
                            that.globalData.vehicleId = res.data.result.records[0].ID;
                            that.globalData.driverId = res.data.result.records[0].driver;
                            that.globalData.plate = res.data.result.records[0].plate;
                          }
                        }
                      })
                    }
                    cb(that.globalData.register);

                    try {
                      // socket.emit('online', {
                      //   name: data.name,
                      //   uid: 'u' + data.ID,
                      //   plate: data.plate,
                      //   vehicle: data.vehicleId
                      // });
                      // socketAT.on('disconnect', function () {
                      //   console.log('socketAT disconnected');
                      //   socketAT.emit('online', {
                      //     name: data.name,
                      //     user_id: 'u' + data.ID,
                      //     plate: data.plate,
                      //     vehicle: data.vehicleId
                      //   });
                      // });
                      // socket.on('lp', function (data) {
                      //   if (data.type == 'checkin' && data.user_id == 'u' + data.ID) {
                      //     plugin.textToSpeech({
                      //       lang: "zh_CN",
                      //       tts: true,
                      //       content: data.plate + '已签到',
                      //       success: function (res) {
                      //         const innerAudioContext = wx.createInnerAudioContext()
                      //         innerAudioContext.autoplay = true
                      //         innerAudioContext.src = res.filename;
                      //         innerAudioContext.onPlay(() => {
                      //           console.log('开始播放')
                      //         })
                      //         innerAudioContext.onError((res) => {
                      //           console.log(res.errMsg)
                      //           console.log(res.errCode)
                      //         })
                      //         console.log("succ tts", res.filename)
                      //       },
                      //       fail: function (res) {
                      //         console.log("fail tts", res)
                      //       }
                      //     })
                      //   }
                      // });
                    } catch (e) {}

                  } else {
                    cb(that.globalData.register);
                  }
                  console.log(that.globalData)


                  that.setWXLocation();
                },
                fail: function (error) {
                  console.log(error);
                  cb(false);
                }
              });
            }else{
              wx.showToast({
                title: '系统异常',
                image: '/images/wrong.png',
                duration: 3000
              });
            }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
          cb(false, false);
        }
      },
      fail: function (msg) {
        console.log(msg)
        cb(false);
      }
    })
  },
  getIdentifyingCode: function (mobile, voice, callback) {
    console.log(mobile)
    var that = this;
    wx.request({
      url: server + '/tencent/wechat/sendMsn/' + mobile,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {},
      success: function (res) {
        console.log(res)
        if (res.data.success) {
          callback(res.data.result);
        }
      },
      fail: function (error) {
        console.log(error)
      }
    })
  },
  //order_id, is_pos, object, object_desc, lalt, address, temperature, humidity, mile, duration, shop_id, warehouse_id, exception
  updateDriverTrace: function (id, object, object_desc, lalt, temperature, humidity, shop_id, warehouse_id, exception, mark, distance, callback) {
    var that = this;
    // var gps, lalt, temperature, humidity, mile, duration;
    // try {
    //   temperature = wx.getStorageSync(id + '_temperature');
    // } catch (e) { }
    // try {
    //   humidity = wx.getStorageSync(id + '_humidity');
    // } catch (e) { }
    // try {
    //   gps = wx.getStorageSync(id + '_gps');
    //   gps = gps.split("|");
    //   lalt = gps[0];
    //   mile = gps[1];
    //   duration = gps[2];
    // } catch (e) { }
    if (lalt == '0,0') {
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude;
          var longitude = res.longitude;
          that.updateDriverTraceSubmit(id, object, object_desc, latitude + ',' + longitude, (Number(temperature) || 'null'), (Number(humidity) || 'null'), exception, shop_id, warehouse_id, mark, that.globalData.mpopenid, (distance == undefined ? 0 : distance), callback);
        }
      });
    } else {
      that.updateDriverTraceSubmit(id, object, object_desc, lalt, (Number(temperature) || 'null'), (Number(humidity) || 'null'), exception, shop_id, warehouse_id, mark, that.globalData.mpopenid, (distance == undefined ? 0 : distance), callback);
    }


  },
  updateDriverTraceSubmit: function (id, object, object_desc, lalt, temperature, humidity, exception, shop_id, warehouse_id, mark, mpopenid, distance, callback) {
    var that = this;
    wx.request({
      url: server + '/wechat/wxapplet/driverTrace',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {
        order_id: id,
        is_pos: 1,
        object: object,
        object_desc: object_desc,
        lalt: lalt,
        temperature: temperature,
        humidity: humidity,
        //mile: mile,
        //duration: duration,
        exception: exception,
        shop_id: shop_id,
        warehouse_id: warehouse_id,
        mark: mark,
        mpopenid: mpopenid,
        distance: distance
      },
      success: function (res) {
        if (res.data.success) {
          console.log(typeof distance)
          var func;
          if (typeof callback && typeof callback == 'function') {
            func = callback;
          };
          if (typeof distance && typeof distance == 'function') {
            func = distance;
          };
          if (func) {
            func(true)
          }
        } else {
          if (func) {
            func(false)
          }
        }
      },
      fail: function (error) {}
    });
  },
  setKeyVal: function (key, value, callback) {
    var that = this;
    wx.request({
      url: server + '/wechat/wxapplet/setKeyVal',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {
        key: key,
        value: value
      },
      success: function (res) {
        if (res.data.success) {
          if (callback) {
            callback(true)
          }
        } else {}
      },
      fail: function (error) {}
    });
  },
  getKeyVal: function (key, callback) {
    var that = this;
    wx.request({
      url: server + '/wechat/wxapplet/getKeyVal',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {
        key: key
      },
      success: function (res) {
        if (res.data.success) {
          if (callback) {
            callback(res.data.data)
          }
        } else {}
      },
      fail: function (error) {}
    });
  },
  isMemberKeyVal: function (key, value, callback) {
    var that = this;
    wx.request({
      url: server + '/wechat/wxapplet/isMemberKeyVal',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {
        key: key,
        value: value
      },
      success: function (res) {
        if (res.data.success) {
          if (callback) {
            callback(res.data.data)
          }
        } else {}
      },
      fail: function (error) {}
    });
  },
  memberKeyVal: function (key, callback) {
    var that = this;
    wx.request({
      url: server + '/wechat/wxapplet/memberKeyVal',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {
        key: key
      },
      success: function (res) {
        if (res.data.success) {
          if (callback) {
            callback(res.data.data)
          }
        } else {}
      },
      fail: function (error) {}
    });
  },
  timeException: function (time, limit) {
    if (!limit) {
      if (new Date() > new Date(time)) {
        return 1;
      } else {
        return 0;
      }
    } else {
      var date = new Date(time);
      date.setMinutes(date.getMinutes() + limit);
      if (new Date() > date) {
        return 1;
      } else {
        return 0;
      }
    }
  },
  formatTime: function (time) {
    if (typeof time !== 'number' || time < 0) {
      return time
    }

    var hour = parseInt(time / 3600)
    time = time % 3600
    var minute = parseInt(time / 60)
    time = time % 60
    var second = time

    return ([minute, second]).map(function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join(':')
  },
  checkOfficialAccounts: function (callback) {
    var that = this;
    wx.request({
      url: server + '/wechat/passport/checkOfficialAccounts',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Cookie': that.globalData.cookie
      },
      data: {
        user_id: that.globalData.user_id,
        unionid: that.globalData.unionid,
      },
      success: function (res) {
        console.log(res);
        callback(res.data.data);
      }
    })
  }
})